package com.itheima.web.response;

import org.apache.commons.io.IOUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/downLoadServlet")
public class DownLoadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取下载的文件名
        String filename = request.getParameter("filename");
        //读取文件
        FileInputStream fis = new FileInputStream("E:\\"+filename);
        //通过respoonse获取字节输出流对象
        ServletOutputStream os = response.getOutputStream();
        //设置响应头 通知浏览器以附件的方式处理返回的数据
        //不同的浏览器，对下载的中文文件名编码支持不一样
        //获取浏览器内核信息
        String agent = request.getHeader("user-agent");
        //按照浏览器内核的不同，分别对原始中文文件名进行编码

        //编译后文件名

        response.setHeader("content-Disposition","attachment;filename="+filename);
        //IO对拷
        IOUtils.copy(fis,os);
        fis.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
